<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Requests\UserRequest;
use App\Http\Requests\PasswordModifyRequest;
use App\Repositories\GroupRepository;
use App\Repositories\UserRepository;
use App\Repositories\DepartmentRepository;
use Illuminate\Contracts\Auth\Guard;
use App\Repositories\OrderRepository;
use App\Services\PHPTree;

class UserController extends AdminController
{

    public function __construct(
        GroupRepository $group, 
        UserRepository $user, 
        DepartmentRepository $department,
        OrderRepository $order
    )
    {
        $this->group = $group;
        $this->user = $user;
        $this->department = $department;
        $this->order = $order;
    }

    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function index(Request $request)
    {
        $condition = $request->except('page');
        $where = collect($condition);

        // 所有部门
        $tree = new PHPTree($this->department->all()->toArray());
        $departmentsTree = $tree->render();
        $departmentsById = $tree->getDataId();
        
        $data = $this->user->paginateList($where);

        return view('admin.user', compact('data', 'where', 'departmentsTree', 'departmentsById', 'department'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return Response
     */
    public function create()
    {
        $group = $this->group->lists('name', 'id');
        $departmentsTree = (new PHPTree($this->department->all()->toArray()))->render();

        return view('admin.user_add', compact('group', 'departmentsTree'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  Request  $request
     * @return Response
     */
    public function store(UserRequest $request)
    {
        $result = $this->user->create($request->all());

        if ($result) {
           return redirect('admin/user')->with('success', '用户添加成功'); 
        }

        return back()->withInput($request->all('password'))->with('error', '用户添加失败');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return Response
     */
    public function edit($id)
    {
        $user  = $this->user->find($id);
        $group = $this->group->lists('name', 'id');
        $departmentsTree = (new PHPTree($this->department->all()->toArray()))->render();

        $department = $this->department->find($user->did);

        return view('admin.user_edit', compact('user', 'group', 'department', 'departmentsTree'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  Request  $request
     * @param  int  $id
     * @return Response
     */
    public function update(UserRequest $request, $id)
    {
        if (!$request->has('status')) {
            $request->merge(['status' => 1]);
        }

        $result = $this->user->updateFind($request->all(), $id);

        if ($result) {

            // 更新部门管理者
            if ($request->input('gid') == 2) {
                $this->department->update(['manager'=>$id], $request->input('region_id'));
            } elseif ($request->input('gid') == 5) {
                $this->department->update(['manager'=>$id], $request->input('department_id'));
            }
            
           return redirect('admin/user')->with('success', '用户修改成功');
        }

        return back()->withInput($request->all())->with('error', '用户添加失败');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return Response
     */
    public function destroy($id)
    {
        // 检查是否权限删除
        $check = $this->user->checkUserDestroy($id);

        if (!$check) {
            flash('error', '该用户还在负责部分订单，请转移关联的订单后再删除');
            return response()->json(['code' => 500]);
        }

        $result = $this->user->delete($id);

        if ($result) {
            flash('success', '用户删除成功');
            return response()->json(['code' => 200]);
        }

        flash('error', '用户删除失败');
        return response()->json(['code' => 500]);
    }

    public function editInfo(Request $request)
    {
        if ($request->isMethod('post')) {
            $result = $this->user->updateFind($request->except('id'), $request->input('id'));
            if ($result) {
               return back()->with('success', '个人信息更新成功');
            }
            return back()->withInput($request->all())->with('error', '个人信息更新失败');
        } else {
            $user = auth()->user();
            return view('admin.userinfo_edit', compact('user'));
        }
    }

    // 修改密码
    public function passwordModify(PasswordModifyRequest $request, Guard $auth)
    {
        $user = $auth->user();

        if ($request->isMethod('post')) {
            $credentials = [
                'username' => $user->username,
                'password' => $request->input('old_password')
            ];
            if (!$auth->validate($credentials)) {
                return back()->with('error', '原始密码错误！');  
            }
            $user->password = bcrypt($request->input('password'));
            $user->save();

            return back()->with('success', '用户密码修改成功！'); 
        } else {
            return view('admin.password_modify', compact('user'));
        }  
    }

    // AJAX获取业务员信息
    public function getSalersAjax()
    {
        return $this->user->getSalersAll();
    }

    // 检查用户名
    public function checkUserName(Request $request)
    {
        $user = $this->user->findBy('username', $request->input('username'));

        if ($user) {
            return '该用户名已存在。';
        }

        return '';
    }

    public function checkEmail(Request $request)
    {
        $user = $this->user->findBy('email', $request->input('email'));

        if ($user) {
            return '该邮箱已被使用。';
        }

        return '';
    }

    // 管理员重置用户密码
    public function resetForce($id)
    {
        $user = $this->user->find($id);

        if (!$user) {
            return '该用户不存在。';
        }

        $user->password = bcrypt(config('system.default_password'));
        $user->save();

        return '';
    }
}
